package com.base.cn.platform.os.controller.web.classes.user;

import com.base.cn.platform.os.common.WebBaseController;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.service.course.classes.ClassesService;
import com.base.cn.platform.os.service.course.cou.buy.CourseBuyRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户个人中心我的班级
 * @author ll
 * @date 2018/5/31 16:31
 */
@Controller
@RequestMapping("/web/uc/class")
public class WebUserClassesController extends WebBaseController {
    @Autowired
    private ClassesService classesService;
    @Autowired
    private CourseBuyRecordService courseBuyRecordService;
    /**
     * 我的班级首页
     */
    @RequestMapping("/index")
    public String toClassPersonal(HttpServletRequest request,Model model) throws Exception {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        List<Map<String,Object>> buyCourseMap = courseBuyRecordService.findCourseBuyRecordByUserId(params,true);
            if (ObjectUtils.isNotEmpty(buyCourseMap)) {
                List<Map<String,Object>> endCourse = new ArrayList<>();
                SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //加上时间
                //必须捕获异常
                for (Map<String,Object> course: buyCourseMap){
                    Date date=sDateFormat.parse(course.get("validTime").toString());
                    if (DateUtils.daysBeforeNow(date)<=0){
                        endCourse.add(course);
                    }
                }
                model.addAttribute("endCourse", endCourse);
            }
        return resultPage("/classes/user/u-class");
    }

    /**
     * 加载与用户相关的班级
     * @param currentPage   分页查询条件
     * @param manage 1 用户所有的班级 2.有管理权限的班级
     */
    @RequestMapping("/ajax/list")
    public String listClassPersonal(HttpServletRequest request,Model model,
                                    @RequestParam(value = "currentPage",required = false,defaultValue = "1") Integer currentPage,
                                    @RequestParam(value = "manage", required = false, defaultValue = "1") Integer manage) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String,Object> dataMap = classesService.findClassesPersonalListPage(userId, currentPage, 6);
        model.addAttribute("dataMap", dataMap);
        return resultPage("/classes/user/u-ajax-class");
    }
}
